//
//  LolaTrackData+Utilities.m
//  LAMapBasicDemo
//
//  Created by 罗亮富 on 2018/1/10.
//  Copyright © 2018年 2Bulu. All rights reserved.
//

#import "GeoData+Relationships.h"
#import <MapGisBusiness/LAGAppMapView.h>
#import <FoundationUtilities/NSObject+Binding.h>
#define POLYLINE_SOURCE_SEG_KEY @"srcSeg"



@implementation TrackSegment (Relationships)

-(TrackPolyline *)polyLineWith2ndValueType:(TrackPolylinePointSecondValueType)valType
                       ofCoordinateSysytem:(LACoordinateSystem)mapType
                          createIfNotExist:(BOOL)create
{
    NSString *key = [NSString stringWithFormat:@"type%dCordSys%d",valType,mapType];
    
    TrackPolyline *retLine = [self bindedObjectForKey:key];
    if(!retLine && create)
    {
        retLine = [LAGTrackPolyLineCreater cachedPolyLineForTrackSegment:self with3rdValueType:valType ofCoordinateSysytem:mapType mapRegion:NULL];
        [self bindObject:retLine forKey:key policy:ObjectBindWeak];
        [retLine bindObject:self forKey:POLYLINE_SOURCE_SEG_KEY policy:ObjectBindWeak];//用strong才能保持住对polyline的引用，
    }
    
    return retLine;
}

-(NSArray<TrackPolyline *> *)allPolyLines
{
    NSMutableArray *marray = [NSMutableArray arrayWithCapacity:5];
    [self enumerateBindedKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) {
        if([obj isKindOfClass:[TrackPolyline class]])
            [marray addObject:obj];
    }];
    
    if(marray.count > 0)
        return marray;
    else
        return nil;
}
@end

@implementation TrackPolyline (Relationships)

-(TrackSegment *)sourceTrackSegment
{
    return [self bindedObjectForKey:POLYLINE_SOURCE_SEG_KEY];
}

-(NSArray<LAGAppMapView *> *)addedToMaps
{
    NSMutableDictionary *orgDic = [self bindedObjectForKey:kLineMapRenderedSources];
    NSMutableDictionary *mDic = [orgDic copy];
    NSMutableArray *ma = [NSMutableArray arrayWithCapacity:mDic.count];
    NSMutableArray *rmKeys = [NSMutableArray arrayWithCapacity:mDic.count];
    
    [mDic enumerateBindedKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        
        WeakReference *refObj = (WeakReference *)key;
        if(refObj.weakObj)
            [ma addObject:refObj.weakObj];
        else
        {
            [rmKeys addObject:refObj];
        }
    }];
    
    if(rmKeys.count > 0)
        [orgDic removeObjectsForKeys:rmKeys];
    
    return ma;
}
-(void)removeFromMapView:(LAGAppMapView *)mapView
{
    [mapView removeOverlay:self];
}
-(void)removeFromAllAddedMaps
{
    NSArray *allMaps = self.addedToMaps;
    for(LAGAppMapView *mapv in allMaps)
    {
        [mapv removeOverlay:self];
    }
}

@end
